<template>
  <div>
    <div style="margin-bottom: 16px">
      <a-button type="primary" icon="plus" @click="openModal">
        添加数据表
      </a-button>
    </div>
    <a-modal title="请选择数据表" :visible="visible" :footer="null" @cancel="visible = false">
      <div style="margin-bottom:20px">
        <a-row span="24">
          <a-col span="12">
            表名：<a-input allowClear v-model="queryParam.name" style="width:70%" placeholder="搜表名">
              <a-icon slot="suffix" type="search" />
            </a-input>
          </a-col>
          <a-col span="12">
            说明：<a-input allowClear v-model="queryParam.desc" style="width:70%" placeholder="搜说明">
              <a-icon slot="suffix" type="search" />
            </a-input>
          </a-col>
        </a-row>
      </div>
      <div class="spin-content">
        已选择&nbsp;
        <a class="f-w-600" v-text="selectedRowKeys.length"></a>
        项&nbsp;
      </div>
      <a-table
        bordered
        :scroll="{ y: 300 }"
        :columns="tabcolumns"
        :data-source="searchdata"
        :pagination="tabpagination"
        rowKey="tableName"
        @change="tableChange"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        size="middle"
      >
      </a-table>
      <a-row style="text-align: center;">
        <a-button type="primary" :disabled="!selectedRowKeys.length" @click="confirmSelection">
          确定选择
        </a-button>
      </a-row>
    </a-modal>
    <a-table :scroll="{ y: 500 }" rowKey="tabname_" :data-source="data" :columns="columns">
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <template slot="type_" slot-scope="text, record">
        <a-select class="select" :value="text" @change="v => onCellChange('type_', record.tabname_, v)">
          <a-select-option v-for="(v, k) in typeList" :key="k" :value="v.value">
            {{ v.name }}
          </a-select-option>
        </a-select>
      </template>
      <template slot="primarykey_" slot-scope="text, record, index">
        <a-select
          class="select"
          :value="text"
          :ref="`primarykey${index}`"
          @change="v => onCellChange('primarykey_', record.tabname_, v)"
        >
          <a-select-option key="" value="">请选择</a-select-option>
          <a-select-option v-for="item in record.fields" :key="item.fieldName" :value="item.fieldName">
            {{ item.fieldName }}
          </a-select-option>
        </a-select>
      </template>
      <template slot="foreignkey_" slot-scope="text, record, index">
        <a-select
          class="select"
          :ref="`foreign${index}`"
          :value="text"
          :disabled="[90400, 90401].includes(record.type_)"
          @change="v => onCellChange('foreignkey_', record.tabname_, v)"
        >
          <a-select-option key="meiYou" value="">无</a-select-option>
          <a-select-option v-for="item in record.fields" :key="item.fieldName" :value="item.fieldName">
            {{ item.fieldName }}
          </a-select-option>
        </a-select>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-popconfirm v-if="data.length" title="确认删除吗?" @confirm="() => onDelete(record.tabname_)">
          <a href="javascript:;">删除</a>
        </a-popconfirm>
      </template>
    </a-table>
  </div>
</template>
<script>
import { Tp_tab } from '@/enumeration/Tp_tab'
import { findTableList, findTableFieldListByDataSourceId } from '@/api/base/table_meta.js'

export default {
  props: {
    datasourceid: {
      type: [Number, String],
      default: null
    },
    tableData: {
      type: Array,
      default: []
    }
  },
  data () {
    return {
      data: [
        // {
        //   tabname_: 'mo_te',
        //   description: '说明...',
        //   type_: 90400,
        //   primarykey_: 'id',
        //   foreignkey_: 'tabname_',
        //   fields: [{ fieldName: '', fieldDescription: '' }]
        // }
      ], // 配置用到的表
      columns: [
        {
          title: '序号',
          width: '100px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '表名',
          dataIndex: 'tabname_',
          width: '',
          align: 'left',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '说明',
          align: 'left',
          dataIndex: 'cnname_'
        },
        {
          title: '类型',
          dataIndex: 'type_',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'type_' }
        },
        {
          title: '主键',
          dataIndex: 'primarykey_',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'primarykey_' }
        },
        {
          title: '外键',
          dataIndex: 'foreignkey_',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'foreignkey_' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      typeList: Tp_tab, // 主表 90400; // 继承主表 90401; // 引用主表 90402; // 从表 90403;
      visible: false,
      selectedRowKeys: [], // 选中的行id
      tabdata: [], // 所有表数据
      tabpagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      queryParam: {
        name: '',
        desc: ''
      },
      tabcolumns: [
        {
          title: '表名',
          align: 'left',
          dataIndex: 'tableName'
        },
        {
          title: '说明',
          align: 'left',
          dataIndex: 'notes',
          ellipsis: true
        }
      ]
    }
  },
  computed: {
    searchdata () {
      return this.tabdata.filter(item => {
        if (!this.queryParam.name && !this.queryParam.desc) {
          return true
        }
        if (this.queryParam.name && this.queryParam.desc) {
          if (item.tableName.indexOf(this.queryParam.name) >= 0 && item.notes.indexOf(this.queryParam.desc) >= 0) {
            return true
          }
        } else {
          if (this.queryParam.name && item.tableName.indexOf(this.queryParam.name) >= 0) {
            return true
          }
          if (this.queryParam.desc && item.notes.indexOf(this.queryParam.desc) >= 0) {
            return true
          }
        }
      })
    }
  },
  async created () {
    // console.log('this.datasourceid', this.datasourceid)
    if (this.tableData.length) {
      this.data = this.tableData
    }
    if (this.datasourceid) {
      await findTableList(this.datasourceid).then(res => {
        console.log('findTableList', res.data)
        if (res.code == 0 && res.data) {
          this.tabdata = res.data
          this.tabpagination.total = res.data.length
        }
      })
    }
  },
  methods: {
    openModal () {
      this.selectedRowKeys = this.data.map(item => item.tabname_)
      this.visible = true
    },
    /**
     * 选中行数据时触发
     */
    onSelectChange (selectedRowKeys) {
      //   console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange (pagination, filters, sorter, { currentDataSource }) {
      //   console.log('pagination', pagination)
      //   console.log('filters', filters)
      //   console.log('sorter', sorter)
      //   console.log('currentDataSource', currentDataSource)
      this.tabpagination.current = pagination.current
    },
    async confirmSelection () {
      const selectedRowKeys = JSON.parse(JSON.stringify(this.selectedRowKeys))
      this.data.forEach(item => {
        const index = selectedRowKeys.indexOf(item.tabname_)
        // console.log('index', index, item.tabname_)
        if (index >= 0) {
          selectedRowKeys.splice(index, 1)
        }
      })
      //   console.log('去除已选的selectedRowKeys', selectedRowKeys)
      //    const tabdata = this.tabdata.filter(item => selectedRowKeys.includes(item.tableName))
      if (!selectedRowKeys.length) {
        this.visible = false
        return
      }
      const res = await findTableFieldListByDataSourceId(this.datasourceid, selectedRowKeys)
      //   console.log('findTableFieldListByDataSourceId', res)
      if (res.code == 0 && res.data) {
        res.data.forEach(item => {
          let cnname = ''
          const target = this.tabdata.find(tab => item.name == tab.tableName)
          if (target) {
            cnname = target.notes
          }
          this.data.push({
            tabname_: item.name,
            cnname_: cnname,
            type_: 90400,
            primarykey_: '',
            foreignkey_: '',
            datasource_: this.datasourceid,
            fields: item.data
          })
        })
        // console.log('添加数据后的this.data', this.data)
        this.visible = false
      }
    },
    onCellChange (key, tablename, value) {
      const data = [...this.data]
      const target = data.find(item => item.tabname_ == tablename)
      if (target) {
        target[key] = value
        if ([90400, 90401].includes(target.type_)) {
          target.foreignkey_ = ''
        }
        this.data = data
      }
      //   console.log('this.data', this.data)
    },
    onDelete (tablename) {
      //   console.log(tablename)
      const data = [...this.data]
      this.data = data.filter(item => item.tabname_ != tablename)

      const index = this.selectedRowKeys.indexOf(tablename)
      if (index >= 0) {
        this.selectedRowKeys.splice(index, 1)
      }
      //   console.log('this.data', this.data)
    },
    validate () {
      if (!this.data.length) {
        this.$message.warning('请至少选择一张表')
        return false
      }
      const mainArr = this.data.filter(item => item.type_ == 90400)
      //   console.log('mainArr', mainArr)
      if (mainArr.length != 1) {
        this.$message.warning('有且只能有一张主表！')
        return false
      }
      const inheritArr = this.data.filter(item => item.type_ == 90401)
      //   console.log('inheritArr', inheritArr)
      const primaryIndex = this.data.findIndex(item => !item.primarykey_)
      if (primaryIndex >= 0) {
        this.$message.warning('请选择主键！')
        this.$refs['primarykey' + primaryIndex].focus()
        // console.log('this.$refs['primarykey' + index]', this.$refs['primarykey' + index])
        return false
      }
      const index = this.data.findIndex(item => [90402, 90403].includes(item.type_) && !item.foreignkey_)
      //   console.log('index', index)
      if (index >= 0) {
        this.$message.warning('引用主表、从表，请选择外键！')
        this.$refs['foreign' + index].focus()
        // console.log('this.$refs[foreign + index]', this.$refs['foreign' + index])
        return false
      }
      return true
    },
    setData () {
      this.$emit('setData', this.data)
    }
  }
}
</script>
<style scoped>
.select {
  min-width: 100px;
}
</style>
